<?php
// +----------------------------------------------------------------------
// | User: zq
// +----------------------------------------------------------------------
// | Time: 2020/12/12 2:24 下午
// +----------------------------------------------------------------------


namespace app\api\controller;

use app\common\controller\Api;
use think\Config;
use think\Db;

class Xcx extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /*
     * 获取openid,并从数据库验证是否绑定
     */
    public function getOpenid()
    {
        $code       = input('get.code');
        $appid      = 'wx08bac7bc0c3c93a7';
        $secret     = '949c7bb7ce29b1919d38221c2b122f18';
        $url        = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $weixin     = file_get_contents($url);
        $jsondecode = json_decode($weixin);
        $array      = get_object_vars($jsondecode);

        $openid = $array['openid'];
        if ($openid) {
            // 根据openid 在后台查询,是否在数据库中
            $ret_findOpenid = Db::name('wxuser')->where('openid', $openid)->find();
            /*
             * bindflag=0,未绑定, bindflag=1,已绑定
             */
            $bindflag = 0;
            if ($ret_findOpenid) {
                //如果有值表示已经绑定
                $bindflag = 1;
            }

            $this->success('获取openid成功', ['openid' => $openid, 'bindflag' => $bindflag, 'openid' => $openid, 'wxuser' => $ret_findOpenid]);

        } else {
            $this->error('获取openid失败', $openid);

        }
    }

    /**
     * 获取菜单
     */
    public function getCaidan($num = 7)
    {
        $openid = input('post.openid');
        /**
         * 根据post.openid来识别
         *  1. post.openid 为空,表示未登录
         *  2. post.openid 不为空,表示登录了,但是还要查询是否绑定
         *     2.1 已经绑定
         *     2.2 未绑定
         */

        //1. post.openid 为空,表示未登录
        if ($openid == '') {
            $this->getCaidanWithNoOpenid($num);
        } else {
            // 查询 fa_wxuser openid是否存在
            $ret_findOpenidFromWxuser = Db::name("wxuser")->where("openid", $openid)->find();
            if ($ret_findOpenidFromWxuser) {
                //已经绑定用户
                $this->getCaidanWithOpenid($num, $openid);
            } else {
                //未绑定用户
                $this->getCaidanWithNoOpenid($num);
            }
        }


    }

    /**
     * 点餐
     * post.yuyuedate 点餐的日期
     * post.openid 用户openid
     * post.zhongwan 中餐还是晚餐
     * post.flag 点击的状态 1=未点,2=已点
     */
    public function setFan()
    {
        $wxuserid = $this->checkOpenid(input('post.openid'));
        if (!$wxuserid || input('post.openid') == '') {
            $this->error('请先绑定用户');
        }


        if (input('post.zhongwan') == 'zhong') {
            $zw   = 'yuyuezhong';
            $zw_2 = 'yuyuewan';
        } elseif (input('post.zhongwan') == 'wan') {
            $zw   = 'yuyuewan';
            $zw_2 = 'yuyuezhong';
        }

        // 查看用户之前是否添加过,没有添加的直接添加一条,如果之前添加过,则修改.
        $find_yuyue = Db::name('yuyue')->where('wxuser_id', $wxuserid)->where('yuyuedate', input('post.yuyuedate'))->where('deletetime', 'null')->select();

        if ($find_yuyue) {
            // 修改
            $ret_flag = Db::name('yuyue')
                ->where('wxuser_id', $wxuserid)
                ->where('yuyuedate', input('post.yuyuedate'))
                ->update(
                    [
                        $zw          => input('post.flag'),
                        'updatetime' => time()
                    ]
                );

        } else {
            // 添加
            $data     = [
                'wxuser_id'  => $wxuserid,
                $zw          => input('post.flag'),
                $zw_2        => 1,
                'yuyuedate'  => input('post.yuyuedate'),
                'createtime' => time(),
                'updatetime' => time()
            ];
            $ret_flag = Db::name('yuyue')
                ->insert($data);
        }

        if ($ret_flag) {
            $this->success('修改成功!');
        } else {
            $this->error('修改失败!');
        }

    }

    /**
     * 在客户没有登录或者没有绑定的时候查询数据
     */
    protected function getCaidanWithNoOpenid($num)
    {
        $ret = Db::name('cai')
            ->field('yuyuedate,zcai1,zcai2,zcai3,zcai4,wcai1,wcai2,wcai3,wcai4')
            ->order('createtime desc')
            ->where('deletetime', null)
            ->limit($num)
            ->select();


        if ($ret) {
            /**
             * 遍历数组,加上是否点餐 yuyuezhong,yuyuewan  1=未点餐,2=已点餐
             * 遍历数组,加上已经登录 bindflag 0=未绑定,1=已绑定
             */
            $ret_cai = $this->setCaidan($ret);
            $this->success('查询成功!', $ret_cai);
        } else {
            $this->error('查询失败!');
        }
    }

    /**
     * 在客户没有登录或者没有绑定的时候查询数据
     */
    protected function getCaidanWithOpenid($num, $openid)
    {
        /**
         * $ret1 是按照日期所有的值
         */
        $ret1 = Db::name('cai')
            ->field('yuyuedate,zcai1,zcai2,zcai3,zcai4,wcai1,wcai2,wcai3,wcai4')
            ->order('createtime desc')
            ->where('deletetime', null)
            ->limit($num)
            ->select();

        /**
         * $ret2 是按照日期,自己点餐的值
         */
        $ret2 = Db::name('cai')
            ->alias('c')
            ->join('fa_yuyue y', 'c.yuyuedate=y.yuyuedate', 'LEFT')
            ->join('fa_wxuser w', 'y.wxuser_id=w.id', 'LEFT')
            ->field('c.yuyuedate,c.zcai1,c.zcai2,c.zcai3,c.zcai4,c.wcai1,c.wcai2,c.wcai3,c.wcai4,y.yuyuezhong,y.yuyuewan')
            ->where('w.openid', $openid)
            ->order('c.createtime desc')
            ->limit($num)
            ->select();

        /**
         * 如果 $ret2中有点餐的值,则直接覆盖$ret1
         */
        foreach ($ret1 as $k1 => $v1) {
            foreach ($ret2 as $k2 => $v2) {
                if ($v2['yuyuedate'] == $v1['yuyuedate']) {
                    $ret1[$k1] = $v2;
                }
            }
        }

        if ($ret1) {
            /**
             * 遍历数组,加上是否点餐 yuyuezhong,yuyuewan  1=未点餐,2=已点餐
             * 遍历数组,加上已经登录 bindflag 0=未绑定,1=已绑定
             */
            $ret_cai = $this->setCaidan($ret1, $openid);
            $this->success('查询成功!-登录且绑定', $ret_cai);
        } else {
            $this->error('查询失败!');
        }
    }

    /**
     * 根据提供的openid来查询是否绑定
     * 如果没有绑定返回 false
     * 如果已经绑定返回 用户id
     */
    protected function checkOpenid($openid)
    {
        $ret = Db::name('wxuser')->where('openid', $openid)->find();
        if ($ret) {
            return $ret['id'];
        } else {
            return false;
        }
    }


    /**
     * 处理数据,在原始数据的基础上加上3个标识,如下
     * 1. 加上今天和明天的标识   istoday 0=不是,1=是今天,2=是明天
     * 2. 加上中午是否点餐的标识 yuyuezhong 1=未点餐,2=已点餐
     * 3. 加上晚上是否点餐的标识 yuyuewan 1=未点餐,2=已点餐
     * 4. 如果请求的参数中有openid说明是绑定过的.如果没有,表示未绑定.
     * 5. 加上截止标签,time_jiezhi_diancan, 1=允许点餐,0=不允许点餐
     */
    protected function setCaidan($arr, $openid = '')
    {
        /**
         * 遍历数组,加上是否点餐 yuyuezhong,yuyuewan  1=未点餐,2=已点餐
         * 遍历数组,加上已经登录 bindflag 0=未绑定,1=已绑定
         */
        $ret                 = $arr;
        $time_jiezhi_diancan = 1;

        $jiezhi_hour = Config::get('site.jiezhi');
        $now_hour    = date('H');

        if ($jiezhi_hour <= $now_hour) {
            $time_jiezhi_diancan = 0;
        }


        foreach ($ret as $k => $v) {
            $ret[$k]['istoday'] = 0;  //是否是今天, 0=不是,1=是今天,2=是明天

            //是否是今天
            if ($v['yuyuedate'] == date("Y-m-d")) {
                $ret[$k]['istoday'] = 1;
            }

            //是否是明日
            if ($v['yuyuedate'] == date("Y-m-d", strtotime("+1 day"))) {
                $ret[$k]['istoday'] = 2;
            }

            if (!isset($v['yuyuezhong']) && !isset($v['yuyuewan'])) {
                $ret[$k]['yuyuezhong'] = 1;
                $ret[$k]['yuyuewan']   = 1;
            }

            if ($openid == '') {
                $ret[$k]['bindflag'] = 0;
            } else {
                $ret[$k]['bindflag'] = 1;
            }

            $ret[$k]['time_jiezhi_diancan'] = $time_jiezhi_diancan;
        }
        return $ret;
    }

    /**
     * 获取今天和明天的早晚点餐人数,餐厅的不计算在内
     */
    public function getRenshu()
    {
        $zhong_renshu_m = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', date('Y-m-d', strtotime('+1 day')))
            ->where('a.yuyuezhong', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->count();
        $wan_renshu_m   = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', date('Y-m-d', strtotime('+1 day')))
            ->where('a.yuyuewan', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->count();
        $zhong_renshu_j = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', date('Y-m-d'))
            ->where('a.yuyuezhong', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->count();
        $wan_renshu_j   = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', date('Y-m-d'))
            ->where('a.yuyuewan', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->count();

        $data['zhong_m'] = $zhong_renshu_m;
        $data['wan_m']   = $wan_renshu_m;
        $data['zhong_j'] = $zhong_renshu_j;
        $data['wan_j']   = $wan_renshu_j;

        $this->success('人数查询成功', $data);
    }

    /**
     * 根据日期查询当天的中午点餐人数和晚上点餐人数
     */
    public function getRenshuByDate($date){
        $zhong_renshu = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', $date)
            ->where('a.yuyuezhong', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->where('a.deletetime', null)
            ->count();
        $wan_renshu   = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', $date)
            ->where('a.yuyuewan', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->where('a.deletetime', null)
            ->count();

        $data[$date]['zhong'] = $zhong_renshu;
        $data[$date]['wan']   = $wan_renshu;

        return $data;
    }

    /**
     * 遍历这个月的日期,然后查询数据
     */
    public function getMonthData(){
        //获取当前年月
        $nowYear = date('Y');
        $nowMonth = date('m')+1;

        $renshuList = array();
        //遍历今年的数据
        for ($i=1; $i<=$nowMonth; $i++){
            $data = Db::name('yuyue')->field('yuyuedate')->group('yuyuedate')->where('yuyuedate', 'between time', [$nowYear.'-'.$i.'-1', $nowYear.'-'.$i.'-31'])->select();

            $monthKey = '';
            foreach ($data as $k => $datum) {
                if($i < 9){
                    $monthKey = '0'.$i;
                }

                $renshuList[$i]['month'] = $nowYear.'-'.$monthKey;
                $renshuList[$i]['value'][$k] = $this->getRenshuByDate($datum['yuyuedate']);
            }
        }

        //dump($renshuList);

        //$renshuList = Db::name('yuyue')->field('yuyuedate')->select();

        $this->success('人数查询成功', $renshuList);
    }


    //通过日期查询点餐的具体人数名单,,餐厅的不计算在内
    public function getMingDanByGroup()
    {
        /**
         * 1. 查询所有人员
         * 2. 查询点餐的用户
         * 3. 上面2次集合合并,点餐给2, 未点餐给1
         */

        // 1. 查询所有人员
        $arr_yonghu = Db::name('wxuser')
            ->where('deletetime', null)
            ->order('zuid asc, id asc')
            ->select();

        // 2. 根据日期查询点餐的人数
        $yuyuedate         = input('post.yuyuedate');
        $arr_youhu_diancan = Db::name('yuyue')
            ->where('yuyuedate', $yuyuedate)
            ->select();

        // 3. 上面2次集合合并,点餐给2, 未点餐给1
        foreach ($arr_yonghu as $k => $v) {
            $arr_yonghu[$k]['yuyuezhong'] = 1;
            $arr_yonghu[$k]['yuyuewan']   = 1;

            foreach ($arr_youhu_diancan as $kk => $vv) {
                if ($vv['wxuser_id'] == $v['id']) {
                    $arr_yonghu[$k]['yuyuezhong'] = $vv['yuyuezhong'];
                    $arr_yonghu[$k]['yuyuewan']   = $vv['yuyuewan'];
                }
            }
        }

        // 4. 点餐的人数,餐厅的不计算在内
        $zhong_num = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', input("post.yuyuedate"))
            ->where('a.yuyuezhong', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->where('a.deletetime', null)
            ->count();
        $wan_num   = Db::name('yuyue')
            ->alias('a')
            ->where('a.yuyuedate', input("post.yuyuedate"))
            ->where('a.yuyuewan', 2)
            ->join('wxuser b', 'a.wxuser_id=b.id')
            ->where('b.state', 'neq', '4')
            ->where('a.deletetime', null)
            ->count();

        $returnArr = array(
            'wanNum'   => $wan_num,
            'zhongNum' => $zhong_num,
            'mingdan'  => $arr_yonghu,
        );

        $this->success('查询成功!', $returnArr);

    }

    /**
     * 获取明日菜单
     */
    public function getTomorrowCaidan()
    {
        //查询今天
        $ret = Db::name('cai')->where('yuyuedate', 'eq', date('Y-m-d', strtotime('+1 day')))->find();
        if ($ret) {
            $this->success('查询明日菜单成功!', $ret);
        } else {
            $this->error('查询失败!');
        }
    }

    /**
     * 上传明日菜单
     * post.openid 用户的openid
     *
     */
    public function uploadCai()
    {
        $wxuserid = $this->checkOpenid(input('post.openid'));
        if (!$wxuserid || input('post.openid') == '') {
            $this->error('请先绑定用户');
        }
        /**
         * 需要查询一下 明天的菜单是否存在,不存在则添加,存在则修改
         */
        $find_caidan = Db::name('cai')->where('yuyuedate', date('Y-m-d', strtotime('+1 day')))->find();

        if ($find_caidan) {
            //存在则修改
            $data = [
                'zcai1'      => input('post.z_cai1'),
                'zcai2'      => input('post.z_cai2'),
                'zcai3'      => input('post.z_cai3'),
                'zcai4'      => input('post.z_cai4'),
                'wcai1'      => input('post.w_cai1'),
                'wcai2'      => input('post.w_cai2'),
                'wcai3'      => input('post.w_cai3'),
                'updatetime' => time()
            ];
            $ret  = Db::name('cai')->where('yuyuedate', date('Y-m-d', strtotime('+1 day')))->update($data);

        } else {
            //不存在则添加
            $data = [
                'zcai1'      => input('post.z_cai1'),
                'zcai2'      => input('post.z_cai2'),
                'zcai3'      => input('post.z_cai3'),
                'zcai4'      => input('post.z_cai4'),
                'wcai1'      => input('post.w_cai1'),
                'wcai2'      => input('post.w_cai2'),
                'wcai3'      => input('post.w_cai3'),
                'yuyuedate'  => date('Y-m-d', strtotime('+1 day')),
                'createtime' => time(),
                'updatetime' => time()
            ];
            //不存在则添加
            $ret = Db::name('cai')->insert($data);
        }


        if ($ret) {
            $this->success('添加成功!');
        } else {
            $this->success('添加失败!');
        }

    }

    /**
     * 绑定账号
     * code=0 绑定失败
     * code=1 绑定成功
     */
    public function setBindUser()
    {
        /**
         * post.user
         * post.pwd
         * post.openid
         */
        //1. 查询 openid 是否存在,如果存在,则表示被他人绑定了.
        $ret = Db::name('wxuser')
            ->where([
                'username' => input('post.user'),
                'password' => md5(input('post.pwd')),
            ])->find();
        if ($ret) {
            if ($ret['openid'] != '') {
                //存在,表示已经被他人绑定了
                $this->error('已经被他人绑定');
            }
        } else {
            $this->error('账号或密码错误');
        }

        //2.查询账号,密码并保持openid
        $ret_update = Db::name('wxuser')
            ->where([
                'username' => input('post.user'),
                'password' => md5(input('post.pwd')),
            ])->update(
                [
                    'openid'     => input('post.openid'),
                    'updatetime' => time()
                ]
            );
        if ($ret_update) {
            //更新之后,把这条数据完整的给到前面
            $user = Db::name('wxuser')->where([
                'username' => input('post.user'),
                'password' => md5(input('post.pwd')),
            ])->find();

            $this->success('绑定成功', $user);
        } else {
            $this->error('绑定失败');
        }


    }

    /**
     * 获取后台自己定义的字段
     * 1. $site.jiezhi 截止时间
     * 2. $site.notice 首页顶部提示信息
     */
    public function getXcxBaseInfo()
    {
        $time   = Config::get('site.jiezhi');
        $notice = Config::get('site.notice');
        $this->success('时间获取成功!', [
            'jiezhitime' => $time,
            'notice'     => $notice
        ]);
    }

    /**
     * 给一个链接,来判断明天是否有值,如果没有值,则添加一条
     */
    public function autoAddTomorrow()
    {
        $find_caidan_tomorrow = Db::name('cai')->where('yuyuedate', date("Y-m-d", strtotime("+1 day")))->find();
        if (!$find_caidan_tomorrow) {
            //不存在则添加
            $data = [
                'zcai1'      => '午餐',
                'wcai1'      => '晚餐',
                'yuyuedate'  => date("Y-m-d", strtotime("+1 day")),
                'createtime' => time(),
                'updatetime' => time()
            ];
            //不存在则添加
            $ret = Db::name('cai')->insert($data);
            if ($ret) {
                $this->success('success');
            }else{
                $this->error('已经存在!忽略');
            }
        }
    }

    /**
     * 方法测试
     */
    public function test()
    {



    }
}